<template>
  <div>
    <BasicTable
      :search-info="searchInfo"
      @register="registerTable"
      title="检查表管理"
      :pagination="false"
      :scroll="{ x: false, y: 'calc(100vh - 300px)' }"
    >
      <template #toolbar>
        <a-button type="primary" @click="onAddCheckFormButtonClick">新增</a-button>
      </template>
      <template #title="{ record }">
        <span @click="onPreviewCheckFormButtonClick(record)">{{ record.title }}</span>
      </template>
      <template #catcode="{ record }"
        >{{ categoryOption.find((item) => item.value == record.catcode)?.label }}
      </template>
      <template #status="{ record }">
        <a-tag v-if="record.status == 0" color="green"> 正常 </a-tag>
        <a-tag v-else-if="record.status == 5" color="red">禁用</a-tag>
        <a-tag v-else>已删除</a-tag>
      </template>
      <template #action="{ column, record }">
        <TableAction
          :actions="[
            {
              icon: 'ant-design:insert-row-above-outlined',
              label: '配置',
              onClick: onPreviewCheckFormButtonClick.bind(null, record),
            },
            {
              icon: 'clarity:note-edit-line',
              label: '编辑',
              onClick: onEditCheckFormButtonClick.bind(null, record),
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              label: '删除',
              popConfirm: {
                title: '是否确认删除',
                placement: 'left',
                confirm: onDeleteCheckFormButtonClick.bind(null, record),
              },
            },
          ]"
        />
      </template>
    </BasicTable>
    <AddOrUpdateCheckForm @register="registerAddOrUpdateCheckFormModal" @success="afterSuccess" />
    <ViewCheckFormGroupModal @register="registerViewCheckFormGroupModal" @success="afterSuccess" />
    <CheckFormDrawer @register="registerCheckForm" mode="preview" @success="afterSuccess" />
  </div>
</template>

<script lang="ts">
  import { defineComponent, onMounted, ref, onBeforeMount } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import { useMessage } from '/@/hooks/web/useMessage';
  const { createMessage } = useMessage();
  import { useGlobSetting } from '/@/hooks/setting';
  import { Tag } from 'ant-design-vue';
  import { useModal } from '/@/components/Modal';
  import { QcUnifyTransToChildProps } from '/#/QcUnify';
  import { OperationTypeEnum } from '/@/enums/appEnum';
  import { queryEnumOptions } from '/@/api/platform/enum';
  import AddOrUpdateCheckForm from './AddOrUpdateCheckForm.vue';
  import { getUserOrganization } from '/@/api/ehs/organization';
  import { checkFormColumns, checkFormTableCondition } from './checkForm.data';
  import { queryCheckForm, deleteCheckForm } from '/@/api/ehs/checkForm';
  import { getAllTaskCategory } from '/@/api/ehs/taskCategory';
  import ViewCheckFormGroupModal from './ViewCheckFormGroupModal.vue';
  import CheckFormDrawer from './CheckFormDrawer.vue';
  import { useDrawer } from '/@/components/Drawer';
  export default defineComponent({
    name: 'CheckFormIndex',
    components: {
      BasicTable,
      TableAction,
      Tag,
      AddOrUpdateCheckForm,
      ViewCheckFormGroupModal,
      CheckFormDrawer,
    },
    setup() {
      const { globalProjectCode } = useGlobSetting();
      const projectCode = ref<String>(globalProjectCode);
      const searchInfo = ref({
        orgcode: '',
      });
      const categoryOption = ref([]);
      const [registerAddOrUpdateCheckFormModal, { openModal: openAddOrUpdateCheckForm }] =
        useModal();
      const [registerCheckForm, { openDrawer: openCheckFormDrawer }] = useDrawer();
      const [registerViewCheckFormGroupModal, { openModal: openViewCheckFormGroupModal }] =
        useModal();
      const [registerTable, { reload, getForm }] = useTable({
        api: queryCheckForm,
        columns: checkFormColumns,
        canResize: true,
        striped: false,
        showTableSetting: true,
        showIndexColumn: true,
        isTreeTable: false,
        bordered: true,
        ellipsis: true,
        immediate: false,
        useSearchForm: true,
        indexColumnProps: {
          width: 50,
        },
        afterFetch: (res) => {
          return res;
        },
        formConfig: {
          schemas: checkFormTableCondition,
          labelWidth: 70,
        },
        actionColumn: {
          width: 280,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
          // fixed: 'right', //表格操作列是否固定，不设置时默认固定在右侧
        },
      });
      /**
       * 弹窗确认操作之后刷新页面
       */
      function afterSuccess() {
        reload();
      }
      /**
       * 打开新增窗口
       */

      function onAddCheckFormButtonClick() {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '检查表管理',
          operateType: OperationTypeEnum.ADD,
          orgcode: searchInfo.value.orgcode,
        };
        openAddOrUpdateCheckForm(true, propsData);
      }
      /**
       * 打开编辑窗口
       * @param record
       */
      function onEditCheckFormButtonClick(record) {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '检查表管理',
          operateType: OperationTypeEnum.EDIT,
          dataId: record.tableid,
          orgcode: searchInfo.value.orgcode,
        };
        openAddOrUpdateCheckForm(true, propsData);
      }

      // 打开查看表的分组弹窗
      function onViewFormGroupButtonClick(record) {
        //构造父组件给子组件传值对象
        let propsData: QcUnifyTransToChildProps = {
          moduleName: '检查表管理',
          operateString: `查看检查表分组(${record.title})`,
          tableid: record.tableid,
        };
        openViewCheckFormGroupModal(true, propsData);
      }

      /**
       * 删除
       * @param record
       */
      function onDeleteCheckFormButtonClick(record) {
        deleteCheckForm(record.tableid)
          .then((res) => {
            console.log('res', res);
            //res判断结果：同时==undefined和null
            if (res == undefined && (res == null || Object.keys(res).length == 0)) {
              createMessage.success('删除成功。', 2);
              afterSuccess();
            }
          })
          .catch((ex) => {
            console.log('catch ', ex);
            createMessage.error(ex.msg);
          });
      }

      function onPreviewCheckFormButtonClick(record) {
        let propsData: QcUnifyTransToChildProps = {
          moduleName: record.title,
          operateString: '检查表配置',
          dataId: record.tableid,
          orgcode: searchInfo.value.orgcode,
        };
        openCheckFormDrawer(true, propsData);
      }

      onMounted(() => {
        getUserOrganization(projectCode.value).then((res) => {
          searchInfo.value.orgcode = res.orgcode;
          reload();
          getAllTaskCategory(searchInfo.value.orgcode).then((res) => {
            categoryOption.value = res
              ? res.map((item) => {
                  return {
                    ...item,
                    label: item.catname,
                    value: item.catcode,
                  };
                })
              : [];
            getForm().updateSchema({
              field: 'catcode',
              componentProps: {
                options: categoryOption.value,
              },
            });
          });
        });
      });
      return {
        searchInfo,
        categoryOption,
        registerAddOrUpdateCheckFormModal,
        registerViewCheckFormGroupModal,
        registerCheckForm,
        registerTable,
        afterSuccess,
        onAddCheckFormButtonClick,
        onEditCheckFormButtonClick,
        onDeleteCheckFormButtonClick,
        onViewFormGroupButtonClick,
        onPreviewCheckFormButtonClick,
      };
    },
  });
</script>

<style scoped></style>
